
package com.isaac.sqlSession;

import com.isaac.pojo.BoundSql;
import com.isaac.pojo.Configuration;
import com.isaac.pojo.MappedStatement;
import com.isaac.utils.GenericTokenParser;
import com.isaac.utils.ParameterMapping;
import com.isaac.utils.ParameterMappingTokenHandler;

import java.beans.IntrospectionException;
import java.beans.PropertyDescriptor;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

public class SimpleExecutor implements Executor{

    private PreparedStatement doHandleSql(Configuration configuration,MappedStatement mappedStatement,Object...params) throws NoSuchFieldException, IllegalAccessException, SQLException, ClassNotFoundException {
        // 1.注册驱动获取连接
        Connection connection = configuration.getDataSource().getConnection();
        // 2.获取sql： select * from user where id = #{id} and name = #{username}
        String sql = mappedStatement.getSql();
        BoundSql boundSql = getBoundSql(sql);

        // 3.获取预处理对象 preparedStatement
        PreparedStatement preparedStatement = connection.prepareStatement(boundSql.getSqlText());

        // 4.设置参数
        String parameterType = mappedStatement.getParameterType();
        Class<?> parameterTypeClass = getClassType(parameterType);

        List<ParameterMapping> parameterMappingList = boundSql.getParameterMappingList();

        for (int i = 0; i < parameterMappingList.size(); i++) {
            ParameterMapping parameterMapping = parameterMappingList.get(i);
            String content = parameterMapping.getContent();

            // 反射
            Field declaredField = parameterTypeClass.getDeclaredField(content);

            // 暴力访问
            declaredField.setAccessible(true);
            Object o = declaredField.get(params[0]);

            // 参数信息注入sql对象
            preparedStatement.setObject(i+1,o);
        }
        return preparedStatement;
    }

    private Class<?> getClassType(String parameterType) throws ClassNotFoundException {
        if (parameterType != null) {
            Class<?> aClass = Class.forName(parameterType);
            return aClass;
        }
        return null;
    }

    @Override
    public <E> List<E> query(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException, IntrospectionException, InstantiationException, InvocationTargetException {
        PreparedStatement preparedStatement = doHandleSql(configuration, mappedStatement, params);

        // 5.执行sql
        ResultSet resultSet = preparedStatement.executeQuery();
        String resultType = mappedStatement.getResultType();
        Class<?> resultTypeClass = Class.forName(resultType);
        ArrayList<E> results = new ArrayList<>();
        // 6.封装结果集
        while(resultSet.next()){
            Object o = resultTypeClass.newInstance();
            ResultSetMetaData metaData = resultSet.getMetaData();
            for (int i = 1; i < metaData.getColumnCount(); i++) {
                // 属性名
                String columnName = metaData.getColumnName(i);
                // 属性值
                Object value = resultSet.getObject(i);
                // 属性描述器，生成读写方法
                PropertyDescriptor propertyDescriptor = new PropertyDescriptor(columnName, resultTypeClass);
                // 获取写方法
                Method writeMethod = propertyDescriptor.getWriteMethod();
                // 向类中写入值
                writeMethod.invoke(o,value);
            }
            results.add((E) o);
        }
        return results;
    }

    /**
     * 完成对#{} 解析：
     * 1. 将#{}用？代替
     * 2. 将解析出#{}值存储
     * @param sql
     * @return
     */
    private BoundSql getBoundSql(String sql) {
        ParameterMappingTokenHandler parameterMappingTokenHandler = new ParameterMappingTokenHandler();
        GenericTokenParser genericTokenParser = new GenericTokenParser("#{", "}", parameterMappingTokenHandler);

        String parseSql = genericTokenParser.parse(sql);
        List<ParameterMapping> parameterMappings = parameterMappingTokenHandler.getParameterMappings();
        BoundSql boundSql = new BoundSql(parseSql, parameterMappings);
        return boundSql;
    }

    @Override
    public int insert(Configuration configuration, MappedStatement mappedStatement, Object... params) throws SQLException, ClassNotFoundException, NoSuchFieldException, IllegalAccessException {
        // 1. 获取预处理预警及连接
        PreparedStatement preparedStatement = doHandleSql(configuration, mappedStatement, params);
        // 2. 执行sql
        int editColumns = preparedStatement.executeUpdate();
        return editColumns;
    }

    @Override
    public int update(Configuration configuration, MappedStatement mappedStatement, Object... params) throws ClassNotFoundException, SQLException, IllegalAccessException, NoSuchFieldException {
        PreparedStatement preparedStatement = doHandleSql(configuration, mappedStatement, params);
        int i = preparedStatement.executeUpdate();
        return i;
    }

    @Override
    public int delete(Configuration configuration, MappedStatement mappedStatement, Object... params) throws ClassNotFoundException, SQLException, IllegalAccessException, NoSuchFieldException {
        PreparedStatement preparedStatement = doHandleSql(configuration,mappedStatement,params);
        return preparedStatement.executeUpdate();
    }
}
